import { asyncRoutes, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

export function filterAsyncMenus(privs) {
  const menus = []
  const buttons = []

  privs.forEach(pv => {
    const tmp = { ...pv }
    if (tmp.type==='button'){
      buttons.push(tmp)
    }else{
      if (tmp.children){
        let gene = filterAsyncMenus(tmp.children)
        tmp.children = gene[0]
        buttons.push(...gene[1])
      }
      menus.push(tmp)
    }
  })

  return [menus,buttons]
}

const state = {
  routes: [],
  addRoutes: [],
  menus:[],
  buttons:[]
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_MENUS:(state,menus)=>{
    state.menus=menus
  },
  SET_BUTTONS:(state,buttons)=>{
    state.buttons=buttons
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  generateMenus({commit}, privs){
    return new Promise(resolve => {
      let geneArr = filterAsyncMenus(privs)
      commit('SET_MENUS',geneArr[0])
      commit('SET_BUTTONS',geneArr[1])
      resolve(geneArr)
    })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
